﻿using Microsoft.Azure.Management.ResourceManager.Fluent;
using System.Drawing.Printing;
using System.Linq.Expressions;
using System.Reflection;

namespace WebAPI.Util;

public static class DBHelper
{
    public static IQueryable<T> DataSorting<T>(IQueryable<T> source, string? sortExpression, string sortDirection)
    {
        if (source == null || string.IsNullOrWhiteSpace(sortExpression)) return source;

        try
        {
            BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;

            PropertyInfo propertyInfo = typeof(T).GetProperty(sortExpression, bindingFlags);

            if (sortExpression == null || propertyInfo == null)
                return source;

            string sortingDir = string.Empty;
            if (string.IsNullOrWhiteSpace(sortDirection) || sortDirection.ToUpper().Trim() == "ASC")
                sortingDir = "OrderBy";
            else
                sortingDir = "OrderByDescending";
            ParameterExpression param = Expression.Parameter(typeof(T), "i");
            //PropertyInfo pi = typeof(T).GetProperty(sortExpression, bindingFlags);
            Type[] types = new Type[2];
            types[0] = typeof(T);
            types[1] = propertyInfo.PropertyType;
            Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortExpression), param));
            IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr);
            return query;
        }
        catch (Exception)
        { 
            return source;
        }
    }
}